# @Time : 2020/7/20 14:19
# @Author : Fioman 
# @Phone : 13149920693

"""
阈值处理是指剔除掉图像内像素值高于一定值或者是低于一定值的像素点.例如:设定阈值是127,然后:
1> 将图像内所有像素值大于127的像素点的值设置为255
2> 将图像内所有像素值小于或者等于127的像素点的值设置为0

通过上述方式得到一幅二值图像,有效的实现了前景和背景的分离.
opencv中,使用threshold()函数进行阈值化处理,该函数的语法格式为:
T,binaryImg = cv.threshold(src,thresh,maxval,type)
cv.THRES_BINARY   当大于thresh的时候,结果取为 maxval, 当小于thresh的时候,结果取为0
cv.THRES_BINARY_INV  当大于thresh的时候,结果取为0,当小于等于thresh的时候,结果取为maxval
cv.THRES_TRUNC  当大于thresh的时候,结果取thresh,当小于或者等于thresh的时候,结果取为0
cv.THRES_TOZERO_INV 当大于thresh的时候,结果取0,当小于或者等于thresh的时候结果不变
cv.THRES_TOZERO  当大于thresh的时候,结果不变,当小于thresh的时候结果为0

"""
import cv2 as cv
import numpy as np

"""
进行一般的二值化处理
"""
img = np.random.randint(0, 256, [4, 5], dtype=np.uint8)
T, binaryImg = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
print("img = \n", img)
print("t = {}".format(T))
print("rst = \n", binaryImg)

lena = cv.imread("lenaColor.png", cv.IMREAD_GRAYSCALE)
cv.imshow("Original", lena)

T, thresImg = cv.threshold(lena, 127, 255, cv.THRESH_BINARY)
print("T1 = {}".format(T))
cv.imshow("thres", thresImg)
cv.waitKey(0)

"""
反阈值化处理,对于大于阈值的像素位置按照0来处理,对于小于阈值的像素位置按照maxval来处理.
和CV.THRES_BINARY刚好是相反的.
"""
img = np.random.randint(0, 256, size=[4, 5], dtype=np.uint8)
T, thresImg = cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)
print("img \n", img)
print("T = {}".format(T))
print("thresImg = \n",thresImg)

lena = cv.imread("lenaColor.png",cv.IMREAD_GRAYSCALE)
T,thresImg = cv.threshold(lena,127,255,cv.THRESH_BINARY_INV)
print("T = {}".format(T))
cv.imshow("thresImg",thresImg)
cv.waitKey(0)

"""
截断阈值处理
THRESH_TRUNC  相当于是这样的,对于大于thresh阈值的,做截断处理,结果值设定为阈值.
对于小于等于thresh的,保持不变.
"""

img = np.random.randint(0,256,size=[4,5],dtype=np.uint8)
T,thresImg  = cv.threshold(img,127,255,cv.THRESH_TRUNC)
print("img = \n",img)
print("T = ",T)
print("thresImg = \n",thresImg)


T,thresImg = cv.threshold(lena,127,255,cv.THRESH_TRUNC)
cv.imshow("ThresLena",thresImg)
cv.waitKey(0)

"""
超阈值处理(cv.thres_to_zero_inv)
超阈值处理,会将大于阈值的像素点的值处理为0,小于或等于该阈值的点像素点保持不变.

低阈值处理(cv.thres_to_zero)
大于阈值的像素保持不变,低于或者等于阈值的像素值,其值将被处理为0
"""















